package com.example.myapplication.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.myapplication.R;

public class SharedPrefences extends AppCompatActivity {

    @SuppressLint("CommitPrefEdits")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shared_prefences);
        //获取数据
        SharedPreferences data = getSharedPreferences("data", MODE_PRIVATE);
        //修改数据
        SharedPreferences.Editor edit = data.edit();
        TextView textView = findViewById(R.id.tv1);
        Button button1 = findViewById(R.id.button1);
        Button button2 = findViewById(R.id.button2);
        EditText editText = findViewById(R.id.et);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String string = editText.getText().toString();
                edit.putString("name",string);
                edit.apply();
                textView.setText(data.getString("name","没有设置成功"));
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edit.remove("name");
                edit.apply();
                textView.setText(data.getString("name","删除成功"));
            }
        });

    }
}